package com.yuyou.tas.util.tool;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.yuyou.tas.util.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class QiniuUtils {

    @Value("${qiniu.ak}")
    private static String qiniu_ak;

    @Value("${qiniu.sk}")
    private static String qiniu_sk;

    @Value("${qiniu.store.bucket}")
    private static String qiniu_store_bucket;

    private static Auth auth = Auth.create("jRWnbp3vjHkZxYrDL2IxndNCHNNI_LgoT32EWsiR", "2CziVOyZhrHSDBWIq2zNG1oZmXypI1fz");

    private static String bucket = "public-bucket";

    private static String cdn = "http://static.yuyou100.com/" ;

    public static String upload(InputStream inputStream, String type ) {
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        StringMap stringMap = new StringMap();
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        stringMap.put("saveKey", key);
        if("voice".equals(type)){//转mp3
            stringMap.put("persistentPipeline", "yuyou1");
            stringMap.put("persistentOps", "avthumb/mp3/ab/128k/ar/44100/acodec/libmp3lame|saveas/" + UrlSafeBase64.encodeToString(bucket + ":" + key + ".mp3")) ;
        }

        String upToken = auth.uploadToken(bucket,null, 1800, stringMap );
        try {
            Response response = uploadManager.put(inputStream, null, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return  cdn +  putRet.key + ("voice".equals(type) ? ".mp3" : StringUtils.EMPTY );
        } catch (QiniuException ex) {
            throw new BusinessException("上传失败",ex);
        }
    }


    /**
     * 下载远程地址，并上传至七牛云
     * @param sourceUrl
     * @return
     */
    public static String upload2Qiniu(String sourceUrl , String type){
        InputStream inputStream = null;
        try {
            //获取远程文件资源
            URL url = new URL(sourceUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream=conn.getInputStream();

            return QiniuUtils.upload(inputStream , type);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
//                    e.printStackTrace();
                }
            }
        }
        return sourceUrl;
    }

}
